package com.frame.compiler.utils;

import android.util.Log;

import com.frame.compiler.widget.ToastUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;


/**
 * 日期工具类
 *
 * @author Comsys-linxiaoqing
 * @ClassName: DateUtil
 * @Description:
 * @date 2015/11/6
 */
public class DateUtil {
    /*
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String time, String pattern) {
        String stamp = dateToStamp(time);
        if (EmptyUtils.isEmpty(stamp)) {
            return "";
        } else {
            return TimeStamp2Date2(stamp, pattern);
        }
    }

    /*
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(time);
            long ts = date.getTime();
            return String.valueOf(ts);
        } catch (Exception e) {

        }
        return "";
    }

    /*
     * 将时间转换为时间戳  "yyyy-MM-dd"
     */
    public static long dateToStamp2(String time,String pattern) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = simpleDateFormat.parse(time);
            long ts = date.getTime();
            return ts;
        } catch (Exception e) {

        }
        return 0;
    }

    /*
     * 将时间转换为时间戳
     */
    public static long dateToStamp2(String time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(time);
            long ts = date.getTime();
            return ts;
        } catch (Exception e) {

        }
        return 0;
    }

    //获取现在时间 事例pattern:"yyyy-MM-dd hh:mm:ss"
    public static String getStringDate(String pattern) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    //获取明天时间 事例pattern:"yyyy-MM-dd"
    public static String getStringTomorrowDate(String pattern) {
        Date date = new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(date);
    }

    /**
     * Java将Unix时间戳转换成指定格式日期字符串
     *
     * @param timestampString 时间戳 如："1473048265";秒级
     * @param formats         要格式化的格式 默认："yyyy-MM-dd HH:mm:ss";
     * @return 返回结果 如："2016-09-05 16:06:42";
     */
    public static String TimeStamp2Date(String timestampString, String formats) {
        Long timestamp = Long.parseLong(timestampString) * 1000;
        String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp));
        return date;
    }

    /**
     * Java将Unix时间戳转换成指定格式日期字符串
     *
     * @param timestampString 时间戳 如："1473048265000";毫秒级
     * @param formats         要格式化的格式 默认："yyyy-MM-dd HH:mm:ss";
     * @return 返回结果 如："2016-09-05 16:06:42";
     */
    public static String TimeStamp2Date2(String timestampString, String formats) {
        if (EmptyUtils.isEmpty(timestampString))return "";
        Long timestamp = Long.parseLong(timestampString);
        String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp));
        return date;
    }

    //获取系统时间的10位的时间戳
    public static String getCurrentTime(long currentTimeMillis) {
        long time = currentTimeMillis / 1000;
        String str = String.valueOf(time);
        return str;
    }

    //  String pTime = "2012-03-12";
    public static String getWeek(String pTime) {
        String Week = "";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(format.parse(pTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            Week = "天";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
            Week = "一";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY) {
            Week = "二";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) {
            Week = "三";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) {
            Week = "四";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
            Week = "五";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
            Week = "六";
        }
        return "周" + Week;
    }

    //获取指定日期的年龄
    public static int getAge(String date) {
        Date birthDay = StrToDate(date, "yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            ToastUtils.show("当前日期有误!");
            return 0;
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                age--;
            }
        }
        return age;
    }

    /**
     * string转成Date类型
     *
     * @param @param  dateString
     * @param @param  format
     * @param @return
     * @return Date
     * @throws
     * @Description:
     */
    public static Date StrToDate(String dateString, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date date = sdf.parse(dateString);
            return date;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    //计算是否是婴儿
    public static boolean isBaby(String date) {
        int ageNum = DateUtil.getAge(date);
        if (ageNum >= 0 && ageNum < 2) {
            return true;
        } else {
            return false;
        }
    }

    //计算是否是儿童
    public static boolean isChild(String date) {
        int ageNum = DateUtil.getAge(date);
        if (ageNum >= 2 && ageNum <= 12) {
            return true;
        } else {
            return false;
        }
    }

    //计算是否是成人
    public static boolean isAdult(String date) {
        int ageNum = DateUtil.getAge(date);
        if (ageNum > 12) {
            return true;
        } else {
            return false;
        }
    }

    //比较两个时间的大小dateFirst：2018-10-12 1:dateFirst时间大 0：一样大 -1：dateSecond大
    public static int compareDate(String dateFirst, String dateSecond) {
        String time1 = dateFirst.replaceAll("-", "");
        String time2 = dateSecond.replaceAll("-", "");
        if (new BigDecimal(time1).subtract(new BigDecimal(time2)).intValue() > 0) {
            return 1;
        } else if (new BigDecimal(time1).subtract(new BigDecimal(time2)).intValue() == 0) {
            return 0;
        } else {
            return -1;
        }
    }

    /*
     *计算time2减去time1的差值 差值只设置 几天 几个小时 或 几分钟
     * 根据差值返回多长之间前或多长时间后
     * */

    public static String getDistanceTime(String time1, String time2, int tag) {
        if (EmptyUtils.isEmpty(time1) || EmptyUtils.isEmpty(time2)) {
            return "时间有误";
        } else {
            return getDistanceTime(dateToStamp2(time1), dateToStamp2(time2), tag);
        }
    }

    public static String getDistanceTime(long time1, long time2, int tag) {
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        long diff = 0;
        String time = "";
        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }
        day = diff / (24 * 60 * 60 * 1000);
        hour = (diff / (60 * 60 * 1000) - day * 24);
        min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);

        if (tag >= 1 && day != 0) {
            time += day + "天";
        }
        if (tag >= 2 && hour != 0) {
            time += hour + "小时";
        }
        if (tag >= 3 && min != 0) {
            time += min + "分钟";
        }
        if (tag >= 4 && sec != 0) {
            time += sec + "秒";
        }
        return time;
    }


    public static String getDistanceTime2(String time1, String time2) {
        if (EmptyUtils.isEmpty(time1) || EmptyUtils.isEmpty(time2)) {
            return "时间有误";
        } else {
            return getDistanceTime2(dateToStamp2(time1), dateToStamp2(time2));
        }
    }

    public static String getDistanceTime2(long time1, long time2) {
        String hourStr, minStr;
        long hour = 0;
        long min = 0;
        long diff = 0;
        String time = "";
        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }

        hour = diff / (60 * 60 * 1000);
        min = diff / (60 * 1000) - hour * 60;

        hourStr = (hour < 10) ? ("0" + hour) : String.valueOf(hour);
        minStr = (min < 10) ? ("0" + min) : String.valueOf(min);

        return hourStr + ":" + minStr;
    }


    //----------------------------根据时间差 算出当前的时间------------------------------------
    private static long currDistantTime;//与系统时间的时间差

    public static void setCurrDistantTime(long time) {
        if (time > 0) {
            currDistantTime = System.currentTimeMillis() - time;
        }
    }

    public static long getCurrDistantTime() {
        long time = System.currentTimeMillis() - currDistantTime;
        if (time <= 0) {
            time = System.currentTimeMillis();
        }
        return time;
    }
    //----------------------------根据时间差 算出当前的时间------------------------------------

    //将时间戳转成 分秒格式
    public static String longToString(long data) {
        String str = "";

        long D = data / (24 * 60 * 60);
        long H = (data % (24 * 60 * 60)) / (60 * 60);
        long M = (data % (24 * 60 * 60) % (60 * 60)) / (60);
        long S = (data % (24 * 60 * 60) % (60 * 60) % (60));
        if (D > 0) {
            str += D + "天";
        }

        if (H > 0) {
            str += (H > 9 ? H : "0" + H) + "时";
        }

        str += (M > 9 ? M : "0" + M) + "分" + (S > 9 ? S : "0" + S) + "秒";

        return str;
    }

    //将时间戳转成 分秒格式
    public static String longToString2(long data) {
        String str = "";

        long D = data / (24 * 60 * 60);
        long H = (data % (24 * 60 * 60)) / (60 * 60);
        long M = (data % (24 * 60 * 60) % (60 * 60)) / (60);
        long S = (data % (24 * 60 * 60) % (60 * 60) % (60));
        if (D > 0) {
            str += D + ":";
        }

        if (H > 0) {
            str += (H > 9 ? H : "0" + H) + ":";
        }

        str += (M > 9 ? M : "0" + M) + ":" + (S > 9 ? S : "0" + S);
        return str;
    }

    //将时间戳转成 分秒格式
    public static String longToString3(int data) {
        String str = "";

        int M = (data % (24 * 60 * 60) % (60 * 60)) / (60);
        int S = (data % (24 * 60 * 60) % (60 * 60) % (60));

//        3′9″
        if (M > 0) {
            str += M + "′";
        }

        str +=S+ "″";
        return str;
    }

    //判断闰年
    public static boolean isLeap() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);//获取年份
        if (((year % 100 == 0) && year % 400 == 0) || ((year % 100 != 0) && year % 4 == 0))
            return true;
        else
            return false;
    }

    //返回当月天数
    public static int getMouthDays() {
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH) + 1;//获取月份

        int days;
        int FebDay = 28;
        if (isLeap())
            FebDay = 29;
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                days = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                days = 30;
                break;
            case 2:
                days = FebDay;
                break;
            default:
                days = 0;
                break;
        }
        return days;
    }

    //获取指定天数的日期数组
    public static ArrayList<String> getNumDate(int num) {
        ArrayList<String> dates = new ArrayList<>();

        Calendar c = Calendar.getInstance();
        for (int i = 0; i < num; i++) {
            dates.add(new SimpleDateFormat("yyyy-MM-dd").format(new Date(c.getTimeInMillis())));
            c.add(Calendar.DAY_OF_MONTH, -1);
        }
        return dates;
    }

    /**
     * 格式化时间（输出类似于 刚刚, 4分钟前, 一小时前, 昨天这样的时间）
     *
     * @param time        需要格式化的时间 如"2014-07-14 19:01:45"
     * @param pattern     输入参数time的时间格式 如:"yyyy-MM-dd HH:mm:ss"
     *                    <p/>
     *                    如果为空则默认使用"yyyy-MM-dd HH:mm:ss"格式
     * @param serviceTime 服务器时间
     * @return time为null，或者时间格式不匹配，输出空字符""(带昨天)
     */
    public static String formatDisplayTime(String time, String pattern, String serviceTime) {
        String display = "";
        int tMin = 60 * 1000;
        int tHour = 60 * tMin;
        int tDay = 24 * tHour;

        if (time != null) {
            if (pattern == null)
                pattern = "yyyy-MM-dd HH:mm:ss";
            try {
                Date tDate = new SimpleDateFormat(pattern).parse(TimeStamp2Date2(time, "yyyy-MM-dd HH:mm:ss"));
                Date today = new SimpleDateFormat(pattern).parse(serviceTime);
                SimpleDateFormat thisYearDf = new SimpleDateFormat("yyyy");
                SimpleDateFormat todayDf = new SimpleDateFormat("yyyy-MM-dd");
                Date thisYear = new Date(thisYearDf.parse(thisYearDf.format(today)).getTime());
                Date yesterday = new Date(todayDf.parse(todayDf.format(today)).getTime());
                Date beforeYes = new Date(yesterday.getTime() - tDay);
                if (tDate != null) {
                    @SuppressWarnings("unused")
                    SimpleDateFormat halfDf = new SimpleDateFormat("MM月dd日");
                    long dTime = today.getTime() - tDate.getTime();
                    if (tDate.before(thisYear)) {
                        display = new SimpleDateFormat("yyyy年MM月dd日").format(tDate);
                    } else {
                        if (dTime < tMin) {
                            display = "刚刚";
                        } else if (dTime < tHour) {
                            display = (int) Math.ceil(dTime / tMin) + "分钟前";
                        } else if (dTime < tDay && tDate.after(yesterday)) {
                            display = (int) Math.ceil(dTime / tHour) + "小时前";
                        } else if (tDate.after(beforeYes) && tDate.before(yesterday)) {
                            display = "昨天  " + new SimpleDateFormat("HH:mm").format(tDate);
                        } else {
                            display = TimeStamp2Date2(String.valueOf(tDate.getTime()), "MM-dd");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return display;
    }

    //(不带昨天)
    public static String formatDisplayTime2(String time, String pattern, String serviceTime) {
        String display = "";
        int tMin = 60 * 1000;
        int tHour = 60 * tMin;
        int tDay = 24 * tHour;

        if (time != null) {
            if (pattern == null)
                pattern = "yyyy-MM-dd HH:mm:ss";
            try {
                Date tDate = new SimpleDateFormat(pattern).parse(TimeStamp2Date2(time, "yyyy-MM-dd HH:mm:ss"));
                Date today = new SimpleDateFormat(pattern).parse(serviceTime);
                SimpleDateFormat todayDf = new SimpleDateFormat("yyyy-MM-dd");
                Date yesterday = new Date(todayDf.parse(todayDf.format(today)).getTime());
                if (tDate != null) {
                    @SuppressWarnings("unused")
                    SimpleDateFormat halfDf = new SimpleDateFormat("MM月dd日");
                    long dTime = today.getTime() - tDate.getTime();
                    if (dTime < tMin) {
                        display = "刚刚";
                    } else if (dTime < tHour) {
                        display = (int) Math.ceil(dTime / tMin) + "分钟前";
                    } else if (dTime < tDay && tDate.after(yesterday)) {
                        display = (int) Math.ceil(dTime / tHour) + "小时前";
                    } else {
                        display = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tDate);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return display;
    }

    public static String formatDisplayTime3(String time, String pattern, String serviceTime) {
        String display = "";
        int tMin = 60 * 1000;
        int tHour = 60 * tMin;
        int tDay = 24 * tHour;

        if (time != null) {
            if (pattern == null)
                pattern = "yyyy-MM-dd HH:mm:ss";
            try {
                Date tDate = new SimpleDateFormat(pattern).parse(time);
                Date today = new SimpleDateFormat(pattern).parse(serviceTime);
                SimpleDateFormat thisYearDf = new SimpleDateFormat("yyyy");
                SimpleDateFormat todayDf = new SimpleDateFormat("yyyy-MM-dd");
                Date thisYear = new Date(thisYearDf.parse(thisYearDf.format(today)).getTime());
                Date yesterday = new Date(todayDf.parse(todayDf.format(today)).getTime());
                Date beforeYes = new Date(yesterday.getTime() - tDay);
                if (tDate != null) {
                    @SuppressWarnings("unused")
                    SimpleDateFormat halfDf = new SimpleDateFormat("MM月dd日");
                    long dTime = today.getTime() - tDate.getTime();
                    if (tDate.before(thisYear)) {
                        display = new SimpleDateFormat("yyyy年MM月dd日").format(tDate);
                    } else {
                        if (dTime < tMin) {
                            display = "刚刚";
                        } else if (dTime < tHour) {
                            display = (int) Math.ceil(dTime / tMin) + "分钟前";
                        } else if (dTime < tDay && tDate.after(yesterday)) {
                            display = (int) Math.ceil(dTime / tHour) + "小时前";
                        } else if (tDate.after(beforeYes) && tDate.before(yesterday)) {
                            display = "昨天  " + new SimpleDateFormat("HH:mm").format(tDate);
                        } else {
                            display = TimeStamp2Date2(String.valueOf(tDate.getTime()), "MM-dd");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return display;
    }
}
